<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ title }} - Speakr</title>
    <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
    <script>
        // Function to apply the theme based on localStorage
        function applyTheme() {
            // Apply dark mode
            const savedMode = localStorage.getItem('darkMode');
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            if (savedMode === 'true' || (savedMode === null && prefersDark)) {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }

            // Apply color scheme
            const savedScheme = localStorage.getItem('colorScheme') || 'blue';
            const isDark = document.documentElement.classList.contains('dark');
            const themePrefix = isDark ? 'theme-dark-' : 'theme-light-';
            
            // Remove all other theme classes
            const themeClasses = ['blue', 'emerald', 'purple', 'rose', 'amber', 'teal'];
            themeClasses.forEach(theme => {
                document.documentElement.classList.remove(`theme-light-${theme}`);
                document.documentElement.classList.remove(`theme-dark-${theme}`);
            });

            // Add the correct theme class
            if (savedScheme !== 'blue') {
                 document.documentElement.classList.add(themePrefix + savedScheme);
            }
        }
        applyTheme();
    </script>
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
        <header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]">
            <h1 class="text-3xl font-bold text-[var(--text-primary)]">
                <a href="{{ url_for('index') }}" class="flex items-center">
                    <img src="{{ url_for('static', filename='img/icon-192x192.png') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">
                    Speakr
                </a>
            </h1>
            <div class="flex items-center space-x-2">
                <button id="darkModeToggle" class="p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200">
                    <i id="darkModeIcon" class="fas fa-moon"></i>
                </button>
                <div class="relative" id="userDropdown">
                    <button id="userDropdownButton" class="flex items-center px-3 py-2 border border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:text-[var(--text-accent)] focus:outline-none">
                        <i class="fas fa-user mr-2"></i>
                        <span>{{ current_user.username }}</span>
                        <i class="fas fa-chevron-down ml-2"></i>
                    </button>
                    <div id="userDropdownMenu" class="hidden absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">
                        <a href="{{ url_for('index') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
                            <i class="fas fa-home mr-2"></i> Home
                        </a>
                        <a href="{{ url_for('account') }}" class="block px-4 py-2 text-[var(--text-accent)] bg-[var(--bg-accent)]">
                            <i class="fas fa-user-circle mr-2"></i> Account
                        </a>
                        {% if current_user.is_admin %}
                        <a href="{{ url_for('admin') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
                            <i class="fas fa-user-shield mr-2"></i> Admin
                        </a>
                        {% endif %}
                        <a href="{{ url_for('logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">
                            <i class="fas fa-sign-out-alt mr-2"></i> Logout
                        </a>
                    </div>
                </div>
            </div>
        </header>

        <main class="flex-grow">
            <div class="bg-[var(--bg-secondary)] p-4 sm:p-6 lg:p-8 rounded-xl shadow-lg border border-[var(--border-primary)]">
                <div class="mb-6 border-b border-[var(--border-primary)] sm:border-b">
                    <nav class="tab-nav -mb-px flex flex-col sm:flex-row sm:space-x-8" aria-label="Tabs">
                        <a href="#" id="tab-account" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b-2 sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-[var(--border-accent)] text-[var(--text-accent)] bg-[var(--bg-tertiary)] sm:bg-transparent">
                            <i class="fas fa-user-circle mr-2"></i><span>Account Information</span>
                        </a>
                        <a href="#" id="tab-shares" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent">
                            <i class="fas fa-share-alt mr-2"></i><span>Shared Transcripts</span>
                        </a>
                        <a href="#" id="tab-tags" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent">
                            <i class="fas fa-tags mr-2"></i><span>Tag Management</span>
                        </a>
                        <a href="#" id="tab-about" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent">
                            <i class="fas fa-info-circle mr-2"></i><span>About</span>
                        </a>
                    </nav>
                </div>

                <div id="content-account">
                    <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Account Information</h2>
                    {% with messages = get_flashed_messages(with_categories=true) %}
                    {% if messages %}
                        {% for category, message in messages %}
                            <div class="mb-4 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">
                                {{ message }}
                            </div>
                        {% endfor %}
                    {% endif %}
                {% endwith %}
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <!-- Left Column: Form -->
                    <div>
                        <form method="POST" action="{{ url_for('account') }}" class="space-y-6">
                            <div class="mb-6">
                                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
                                <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Personal Information</h3>
                                <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] space-y-4">
                                    <div>
                                        <label for="user_name" class="block text-sm font-medium text-[var(--text-muted)]">Full Name</label>
                                        <input type="text" name="user_name" id="user_name" value="{{ current_user.name or '' }}" placeholder="Your full name" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
                                    </div>
                                    <div>
                                        <label for="user_job_title" class="block text-sm font-medium text-[var(--text-muted)]">Job Title</label>
                                        <input type="text" name="user_job_title" id="user_job_title" value="{{ current_user.job_title or '' }}" placeholder="e.g., Software Engineer" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
                                    </div>
                                    <div>
                                        <label for="user_company" class="block text-sm font-medium text-[var(--text-muted)]">Company / Organization</label>
                                        <input type="text" name="user_company" id="user_company" value="{{ current_user.company or '' }}" placeholder="e.g., Acme Corp" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
                                    </div>
                                </div>
                            </div>

                            <div class="mb-6">
                                <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Language & Prompt Preferences</h3>
                                <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] space-y-4">
                                    <div>
                                        <label for="transcription_language" class="block text-sm font-medium text-[var(--text-muted)]">Transcription Language</label>
                                        <input type="text" name="transcription_language" id="transcription_language" value="{{ current_user.transcription_language or '' }}" placeholder="e.g., en, es, zh (ISO 639-1 code)" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
                                        <p class="text-xs text-[var(--text-light)] mt-1">Leave blank for auto-detection by transcription service.</p>
                                    </div>
                                    <div>
                                        <label for="output_language" class="block text-sm font-medium text-[var(--text-muted)]">Preferred Output Language</label>
                                        <input type="text" name="output_language" id="output_language" value="{{ current_user.output_language or '' }}" placeholder="e.g., English, Spanish, Chinese" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
                                        <p class="text-xs text-[var(--text-light)] mt-1">Language for titles, summaries, and chat. Leave blank for default (default behavior of your chosen model).</p>
                                    </div>
                                    <div>
                                        <label for="summary_prompt" class="block text-sm font-medium text-[var(--text-muted)]">Custom Summary Prompt</label>
                                        <textarea name="summary_prompt" id="summary_prompt" rows="6" placeholder="Describe how you want your summaries structured. Leave blank to use the default prompt." class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">{{ current_user.summary_prompt or default_summary_prompt_text }}</textarea>
                                        <p class="text-xs text-[var(--text-light)] mt-1">This prompt will be used to generate the summary for your transcriptions. You can use placeholders like {{transcription}} and {{language_directive}} if needed, though the system will try to intelligently place the transcription content.</p>
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" class="w-full inline-flex items-center justify-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
                                <i class="fas fa-save mr-2"></i> Save All Preferences
                            </button>
                        </form>
                    </div>
                    
                    <!-- Right Column: Stats, User Details, Account Actions -->
                    <div class="space-y-6">
                        <div>
                            <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Account Statistics</h3>
                            <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
                                <div class="grid grid-cols-2 gap-4">
                                    <div class="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
                                        <span class="block text-3xl font-bold text-[var(--text-accent)]">{{ current_user.recordings|length }}</span>
                                        <span class="block text-sm text-[var(--text-muted)]">Total Recordings</span>
                                    </div>
                                    
                                    <div class="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
                                        <span class="block text-3xl font-bold text-[var(--text-accent)]">
                                            {% set completed_count = current_user.recordings|selectattr('status', 'equalto', 'COMPLETED')|list|length %}
                                            {{ completed_count }}
                                        </span>
                                        <span class="block text-sm text-[var(--text-muted)]">Completed</span>
                                    </div>
                                    
                                    <div class="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
                                        <span class="block text-3xl font-bold text-[var(--text-warn-strong)]">
                                            {% set processing_count = current_user.recordings|selectattr('status', 'in', ['PENDING', 'PROCESSING', 'SUMMARIZING'])|list|length %}
                                            {{ processing_count }}
                                        </span>
                                        <span class="block text-sm text-[var(--text-muted)]">Processing</span>
                                    </div>
                                    
                                    <div class="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
                                        <span class="block text-3xl font-bold text-[var(--text-danger)]">
                                            {% set failed_count = current_user.recordings|selectattr('status', 'equalto', 'FAILED')|list|length %}
                                            {{ failed_count }}
                                        </span>
                                        <span class="block text-sm text-[var(--text-muted)]">Failed</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="mt-6"> <!-- Added mt-6 for spacing, was mb-6 on User Details -->
                            <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">User Details</h3>
                            <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
                                <div class="mb-3">
                                    <span class="block text-sm font-medium text-[var(--text-muted)]">Username</span>
                                    <span class="block text-[var(--text-primary)]">{{ current_user.username }}</span>
                                </div>
                                <div class="mb-3">
                                    <span class="block text-sm font-medium text-[var(--text-muted)]">Email</span>
                                    <span class="block text-[var(--text-primary)]">{{ current_user.email }}</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-6"> <!-- Added mt-6 for spacing, was mt-8 on Account Actions -->
                            <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Account Actions</h3>
                            <div class="flex flex-col space-y-3">
                                <a href="{{ url_for('index') }}" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
                                    <i class="fas fa-microphone mr-2"></i> Go to Recordings
                                </a>
                                <button id="changePasswordBtn" class="inline-flex items-center px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
                                    <i class="fas fa-key mr-2"></i> Change Password
                                </button>
                                <button id="manageSpeakersBtn" class="inline-flex items-center px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
                                    <i class="fas fa-users mr-2"></i> Manage Speakers
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                </div>

                <div id="content-shares" class="hidden">
                    <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">My Shared Transcripts</h2>
                    <div id="shares-container" class="space-y-4">
                        <!-- Shares will be loaded here by JavaScript -->
                    </div>
                </div>

                <div id="content-tags" class="hidden">
                    <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Tag Management</h2>
                    
                    <div class="mb-6">
                        <div class="flex justify-between items-center mb-4">
                            <p class="text-[var(--text-secondary)]">Organize your recordings with custom tags. Each tag can have its own summary prompt and default ASR settings.</p>
                            <button id="createTagBtn" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
                                <i class="fas fa-plus mr-2"></i> Create Tag
                            </button>
                        </div>
                        
                        <!-- Loading state -->
                        <div id="tagsLoading" class="text-center py-8 hidden">
                            <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
                            <p class="text-[var(--text-muted)] mt-2">Loading tags...</p>
                        </div>
                        
                        <!-- Error state -->
                        <div id="tagsError" class="hidden bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] p-3 rounded-lg mb-4">
                            <i class="fas fa-exclamation-triangle mr-2"></i>
                            <span id="tagsErrorMessage">Failed to load tags</span>
                        </div>
                        
                        <!-- Empty state -->
                        <div id="tagsEmpty" class="text-center py-12 hidden">
                            <i class="fas fa-tags text-4xl text-[var(--text-light)] mb-4"></i>
                            <p class="text-[var(--text-muted)] text-lg mb-2">No tags created yet</p>
                            <p class="text-sm text-[var(--text-light)]">Create your first tag to organize your recordings</p>
                        </div>
                        
                        <!-- Tags grid -->
                        <div id="tagsGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <!-- Tags will be populated here -->
                        </div>
                    </div>
                </div>

                <div id="content-about" class="hidden">
                    <div class="space-y-8">
                        <!-- Header Section -->
                        <div class="text-center">
                            <div class="flex items-center justify-center mb-4">
                                <img src="{{ url_for('static', filename='img/icon-192x192.png') }}" alt="Speakr Logo" class="h-16 w-16 mr-4">
                                <div>
                                    <h2 class="text-3xl font-bold text-[var(--text-primary)]">Speakr</h2>
                                    <p class="text-[var(--text-secondary)]">AI-Powered Audio Transcription & Note-Taking</p>
                                </div>
                            </div>
                            <div class="inline-flex items-center px-3 py-1 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-full text-sm font-medium">
                                <i class="fas fa-tag mr-2"></i>
                                Version <span id="system-version" class="ml-1 font-mono">Loading...</span>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                            <!-- System Information -->
                            <div class="bg-[var(--bg-secondary)] rounded-xl p-6 border border-[var(--border-primary)] shadow-sm">
                                <div class="flex items-center mb-4">
                                    <div class="p-2 bg-[var(--bg-accent)] rounded-lg mr-3">
                                        <i class="fas fa-cogs text-[var(--text-accent)] text-lg"></i>
                                    </div>
                                    <h3 class="text-xl font-semibold text-[var(--text-primary)]">System Configuration</h3>
                                </div>
                                
                                <div class="space-y-4">
                                    <div class="border-l-4 border-[var(--border-accent)] pl-4">
                                        <h4 class="font-medium text-[var(--text-primary)] mb-2">Large Language Model</h4>
                                        <div class="space-y-1 text-sm">
                                            <p class="text-[var(--text-secondary)]">
                                                <span class="font-medium">Model:</span> 
                                                <span id="llm-model" class="font-mono text-[var(--text-primary)] bg-[var(--bg-tertiary)] px-2 py-1 rounded ml-1">Loading...</span>
                                            </p>
                                            <p class="text-[var(--text-secondary)]">
                                                <span class="font-medium">Endpoint:</span> 
                                                <span id="llm-endpoint" class="font-mono text-xs text-[var(--text-muted)] break-all ml-1">Loading...</span>
                                            </p>
                                        </div>
                                    </div>
                                    
                                    <div class="border-l-4 border-green-500 pl-4">
                                        <h4 class="font-medium text-[var(--text-primary)] mb-2">Speech Recognition</h4>
                                        <div class="space-y-1 text-sm">
                                            <p class="text-[var(--text-secondary)]">
                                                <span class="font-medium">Whisper API:</span> 
                                                <span id="whisper-endpoint" class="font-mono text-xs text-[var(--text-muted)] ml-1">Loading...</span>
                                            </p>
                                            <p class="text-[var(--text-secondary)]">
                                                <span class="font-medium">ASR Enabled:</span> 
                                                <span id="asr-status" class="ml-1">Loading...</span>
                                            </p>
                                            <div id="asr-endpoint-row" style="display: none;">
                                                <p class="text-[var(--text-secondary)]">
                                                    <span class="font-medium">ASR Endpoint:</span> 
                                                    <span id="asr-endpoint" class="font-mono text-xs text-[var(--text-muted)] ml-1">-</span>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Project Information -->
                            <div class="bg-[var(--bg-secondary)] rounded-xl p-6 border border-[var(--border-primary)] shadow-sm">
                                <div class="flex items-center mb-4">
                                    <div class="p-2 bg-gray-800 rounded-lg mr-3">
                                        <i class="fab fa-github text-white text-lg"></i>
                                    </div>
                                    <h3 class="text-xl font-semibold text-[var(--text-primary)]">Project Links</h3>
                                </div>
                                
                                <div class="space-y-3">
                                    <a href="https://github.com/murtaza-nasir/speakr" target="_blank" rel="noopener noreferrer" 
                                       class="flex items-center p-3 bg-gray-800 hover:bg-gray-700 text-white rounded-lg transition-all duration-200 group transform hover:scale-[1.02]">
                                        <i class="fab fa-github text-xl mr-3"></i>
                                        <div class="flex-1">
                                            <div class="font-medium">GitHub Repository</div>
                                            <div class="text-sm text-gray-300">Source code, issues, and releases</div>
                                        </div>
                                        <i class="fas fa-external-link-alt text-sm opacity-70 group-hover:opacity-100"></i>
                                    </a>
                                    
                                    <a href="https://hub.docker.com/r/learnedmachine/speakr" target="_blank" rel="noopener noreferrer"
                                       class="flex items-center p-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-all duration-200 group transform hover:scale-[1.02]">
                                        <i class="fab fa-docker text-xl mr-3"></i>
                                        <div class="flex-1">
                                            <div class="font-medium">Docker Hub</div>
                                            <div class="text-sm text-blue-100">Official Docker images</div>
                                        </div>
                                        <i class="fas fa-external-link-alt text-sm opacity-70 group-hover:opacity-100"></i>
                                    </a>
                                    
                                    <a href="https://github.com/murtaza-nasir/speakr/wiki" target="_blank" rel="noopener noreferrer"
                                       class="flex items-center p-3 bg-green-600 hover:bg-green-500 text-white rounded-lg transition-all duration-200 group transform hover:scale-[1.02]">
                                        <i class="fas fa-book text-xl mr-3"></i>
                                        <div class="flex-1">
                                            <div class="font-medium">Documentation</div>
                                            <div class="text-sm text-green-100">Setup guides and user manual</div>
                                        </div>
                                        <i class="fas fa-external-link-alt text-sm opacity-70 group-hover:opacity-100"></i>
                                    </a>
                                </div>
                                
                                <div class="mt-6 p-3 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">
                                    <p class="text-sm text-[var(--text-secondary)] leading-relaxed">
                                        <i class="fas fa-info-circle text-[var(--text-accent)] mr-2"></i>
                                        Transform your audio recordings into organized, searchable notes with AI-powered transcription, summarization, and interactive chat features.
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Key Features -->
                        <div class="bg-[var(--bg-secondary)] rounded-xl p-6 border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center mb-6">
                                <div class="p-2 bg-purple-600 rounded-lg mr-3">
                                    <i class="fas fa-star text-white text-lg"></i>
                                </div>
                                <h3 class="text-xl font-semibold text-[var(--text-primary)]">Key Features</h3>
                            </div>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">
                                    <div class="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg mr-3 mt-1">
                                        <i class="fas fa-microphone text-blue-600 dark:text-blue-400"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-[var(--text-primary)] mb-1">Audio Transcription</h4>
                                        <p class="text-sm text-[var(--text-secondary)]">Whisper API and custom ASR support with high accuracy</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">
                                    <div class="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg mr-3 mt-1">
                                        <i class="fas fa-robot text-purple-600 dark:text-purple-400"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-[var(--text-primary)] mb-1">AI Summarization</h4>
                                        <p class="text-sm text-[var(--text-secondary)]">OpenRouter and Ollama integration with custom prompts</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">
                                    <div class="p-2 bg-green-100 dark:bg-green-900 rounded-lg mr-3 mt-1">
                                        <i class="fas fa-users text-green-600 dark:text-green-400"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-[var(--text-primary)] mb-1">Speaker Diarization</h4>
                                        <p class="text-sm text-[var(--text-secondary)]">Identify and label different speakers automatically</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">
                                    <div class="p-2 bg-orange-100 dark:bg-orange-900 rounded-lg mr-3 mt-1">
                                        <i class="fas fa-comments text-orange-600 dark:text-orange-400"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-[var(--text-primary)] mb-1">Interactive Chat</h4>
                                        <p class="text-sm text-[var(--text-secondary)]">Chat with your transcriptions using AI</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">
                                    <div class="p-2 bg-indigo-100 dark:bg-indigo-900 rounded-lg mr-3 mt-1">
                                        <i class="fas fa-search text-indigo-600 dark:text-indigo-400"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-[var(--text-primary)] mb-1">Inquire Mode</h4>
                                        <p class="text-sm text-[var(--text-secondary)]">Semantic search across all your recordings</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">
                                    <div class="p-2 bg-teal-100 dark:bg-teal-900 rounded-lg mr-3 mt-1">
                                        <i class="fas fa-share-alt text-teal-600 dark:text-teal-400"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-[var(--text-primary)] mb-1">Sharing & Export</h4>
                                        <p class="text-sm text-[var(--text-secondary)]">Share recordings and export to various formats</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Technology Stack -->
                        <div class="bg-[var(--bg-secondary)] rounded-xl p-6 border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center mb-4">
                                <div class="p-2 bg-red-500 rounded-lg mr-3">
                                    <i class="fas fa-code text-white text-lg"></i>
                                </div>
                                <h3 class="text-xl font-semibold text-[var(--text-primary)]">Technology Stack</h3>
                            </div>
                            
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                <div class="text-center p-3 bg-[var(--bg-tertiary)] rounded-lg">
                                    <i class="fab fa-python text-3xl text-blue-500 mb-2"></i>
                                    <p class="text-sm font-medium text-[var(--text-primary)]">Python Flask</p>
                                    <p class="text-xs text-[var(--text-muted)]">Backend</p>
                                </div>
                                <div class="text-center p-3 bg-[var(--bg-tertiary)] rounded-lg">
                                    <i class="fab fa-vuejs text-3xl text-green-500 mb-2"></i>
                                    <p class="text-sm font-medium text-[var(--text-primary)]">Vue.js</p>
                                    <p class="text-xs text-[var(--text-muted)]">Frontend</p>
                                </div>
                                <div class="text-center p-3 bg-[var(--bg-tertiary)] rounded-lg">
                                    <i class="fas fa-database text-3xl text-purple-500 mb-2"></i>
                                    <p class="text-sm font-medium text-[var(--text-primary)]">SQLite</p>
                                    <p class="text-xs text-[var(--text-muted)]">Database</p>
                                </div>
                                <div class="text-center p-3 bg-[var(--bg-tertiary)] rounded-lg">
                                    <i class="fab fa-docker text-3xl text-blue-600 mb-2"></i>
                                    <p class="text-sm font-medium text-[var(--text-primary)]">Docker</p>
                                    <p class="text-xs text-[var(--text-muted)]">Deployment</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">
            <span id="footer-text">Speakr &copy; {{ now.year }}</span>
        </footer>
    </div>

    <!-- Change Password Modal -->
    <div id="changePasswordModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold text-[var(--text-primary)]">Change Password</h3>
                <button id="closeModalBtn" class="text-[var(--text-light)] hover:text-[var(--text-muted)] text-2xl leading-none">&times;</button>
            </div>
            <form id="changePasswordForm" method="POST" action="{{ url_for('change_password') }}">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
                <div class="mb-4">
                    <label for="current_password" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Current Password</label>
                    <input type="password" id="current_password" name="current_password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                </div>
                <div class="mb-4">
                    <label for="new_password" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">New Password</label>
                    <input type="password" id="new_password" name="new_password" required minlength="8" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    <p class="text-xs text-[var(--text-muted)] mt-1">Password must be at least 8 characters long</p>
                </div>
                <div class="mb-6">
                    <label for="confirm_password" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Confirm New Password</label>
                    <input type="password" id="confirm_password" name="confirm_password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancelBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--border-secondary)]">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">Change Password</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Manage Speakers Modal -->
    <div id="manageSpeakersModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold text-[var(--text-primary)]">Manage Speakers</h3>
                <button id="closeSpeakersModalBtn" class="text-[var(--text-light)] hover:text-[var(--text-muted)] text-2xl leading-none">&times;</button>
            </div>
            
            <div class="mb-4">
                <p class="text-sm text-[var(--text-muted)] mb-4">
                    Manage your saved speakers. These are automatically saved when you use speaker names in your recordings.
                </p>
                
                <!-- Loading state -->
                <div id="speakersLoading" class="text-center py-8 hidden">
                    <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
                    <p class="text-[var(--text-muted)] mt-2">Loading speakers...</p>
                </div>
                
                <!-- Error state -->
                <div id="speakersError" class="hidden bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] p-3 rounded-lg mb-4">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    <span id="speakersErrorMessage">Failed to load speakers</span>
                </div>
                
                <!-- Empty state -->
                <div id="speakersEmpty" class="text-center py-8 hidden">
                    <i class="fas fa-users text-4xl text-[var(--text-light)] mb-4"></i>
                    <p class="text-[var(--text-muted)]">No speakers saved yet</p>
                    <p class="text-sm text-[var(--text-light)]">Speakers will appear here when you use speaker names in your recordings</p>
                </div>
                
                <!-- Speakers list -->
                <div id="speakersList" class="space-y-2 max-h-96 overflow-y-auto">
                    <!-- Speakers will be populated here -->
                </div>
            </div>
            
            <div class="flex justify-between items-center pt-4 border-t border-[var(--border-primary)]">
                <div class="text-sm text-[var(--text-muted)]">
                    <span id="speakersCount">0</span> speakers saved
                </div>
                <div class="flex space-x-3">
                    <button id="deleteAllSpeakersBtn" class="px-4 py-2 bg-[var(--bg-danger)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-danger-hover)] disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                        <i class="fas fa-trash mr-2"></i> Delete All
                    </button>
                    <button id="closeSpeakersBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--border-secondary)]">
                        Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete All Speakers Confirmation Modal -->
    <div id="deleteAllSpeakersModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-60 hidden">
        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
            <div class="flex items-center mb-4">
                <i class="fas fa-exclamation-triangle text-[var(--text-danger)] text-2xl mr-3"></i>
                <h3 class="text-xl font-semibold text-[var(--text-primary)]">Delete All Speakers</h3>
            </div>
            <p class="text-[var(--text-secondary)] mb-6">
                Are you sure you want to delete all saved speakers? This action cannot be undone.
            </p>
            <div class="flex justify-end space-x-3">
                <button id="cancelDeleteAllBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--border-secondary)]">
                    Cancel
                </button>
                <button id="confirmDeleteAllBtn" class="px-4 py-2 bg-[var(--bg-danger)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-danger-hover)]">
                    <i class="fas fa-trash mr-2"></i> Delete All
                </button>
            </div>
        </div>
    </div>

    <!-- Create/Edit Tag Modal -->
    <div id="tagModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 id="tagModalTitle" class="text-xl font-semibold text-[var(--text-primary)]">Create Tag</h3>
                <button id="closeTagModalBtn" class="text-[var(--text-light)] hover:text-[var(--text-muted)] text-2xl leading-none">&times;</button>
            </div>
            
            <form id="tagForm" class="space-y-4">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
                <input type="hidden" id="tagId" name="tag_id">
                
                <div>
                    <label for="tagName" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Tag Name *</label>
                    <input type="text" id="tagName" name="name" required maxlength="50" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., Meetings, Interviews">
                </div>
                
                <div>
                    <label for="tagColor" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Color</label>
                    <div class="flex items-center space-x-3">
                        <input type="color" id="tagColor" name="color" value="#3B82F6" class="w-12 h-10 rounded border border-[var(--border-secondary)]">
                        <span class="text-sm text-[var(--text-muted)]">Choose a color for easy identification</span>
                    </div>
                </div>
                
                <div>
                    <label for="tagCustomPrompt" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Custom Summary Prompt</label>
                    <textarea id="tagCustomPrompt" name="custom_prompt" rows="4" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Optional: Custom prompt for generating summaries for recordings with this tag"></textarea>
                    <p class="text-xs text-[var(--text-light)] mt-1">Leave blank to use your default summary prompt</p>
                </div>
                
                {% if use_asr_endpoint %}
                <div class="border-t border-[var(--border-primary)] pt-4">
                    <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">ASR Default Settings</h4>
                    <p class="text-xs text-[var(--text-light)] mb-3">These settings will be applied by default when using this tag with ASR transcription</p>
                    
                    <div class="space-y-3">
                        <div>
                            <label for="tagLanguage" class="block text-sm font-medium text-[var(--text-muted)] mb-1">Default Language</label>
                            <input type="text" id="tagLanguage" name="default_language" maxlength="10" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., en, es, zh">
                        </div>
                        
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label for="tagMinSpeakers" class="block text-sm font-medium text-[var(--text-muted)] mb-1">Min Speakers</label>
                                <input type="number" id="tagMinSpeakers" name="default_min_speakers" min="1" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
                            </div>
                            
                            <div>
                                <label for="tagMaxSpeakers" class="block text-sm font-medium text-[var(--text-muted)] mb-1">Max Speakers</label>
                                <input type="number" id="tagMaxSpeakers" name="default_max_speakers" min="1" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                            </div>
                        </div>
                    </div>
                </div>
                {% endif %}
                
                <div class="flex justify-end space-x-3 pt-4 border-t border-[var(--border-primary)]">
                    <button type="button" id="cancelTagBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--border-secondary)]">Cancel</button>
                    <button type="submit" id="saveTagBtn" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
                        <i class="fas fa-save mr-2"></i> Save Tag
                    </button>
                </div>
            </form>
        </div>
    </div>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const tabAccount = document.getElementById('tab-account');
            const tabShares = document.getElementById('tab-shares');
            const tabTags = document.getElementById('tab-tags');
            const tabAbout = document.getElementById('tab-about');
            const contentAccount = document.getElementById('content-account');
            const contentShares = document.getElementById('content-shares');
            const contentTags = document.getElementById('content-tags');
            const contentAbout = document.getElementById('content-about');
            const sharesContainer = document.getElementById('shares-container');
            

            function showAccountTab() {
                tabAccount.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabAccount.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                contentAccount.classList.remove('hidden');
                contentShares.classList.add('hidden');
                contentTags.classList.add('hidden');
                contentAbout.classList.add('hidden');
            }

            function showSharesTab() {
                tabShares.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabShares.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAccount.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                contentShares.classList.remove('hidden');
                contentAccount.classList.add('hidden');
                contentTags.classList.add('hidden');
                contentAbout.classList.add('hidden');
                loadShares();
            }

            function showTagsTab() {
                tabTags.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabTags.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAccount.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                contentTags.classList.remove('hidden');
                contentAccount.classList.add('hidden');
                contentShares.classList.add('hidden');
                contentAbout.classList.add('hidden');
                loadTags();
            }

            function showAboutTab() {
                tabAbout.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabAbout.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAccount.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
                tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
                contentAbout.classList.remove('hidden');
                contentAccount.classList.add('hidden');
                contentShares.classList.add('hidden');
                contentTags.classList.add('hidden');
                loadSystemInfo();
            }

            tabAccount.addEventListener('click', (e) => {
                e.preventDefault();
                showAccountTab();
            });

            tabShares.addEventListener('click', (e) => {
                e.preventDefault();
                showSharesTab();
            });

            tabTags.addEventListener('click', (e) => {
                e.preventDefault();
                showTagsTab();
            });

            tabAbout.addEventListener('click', (e) => {
                e.preventDefault();
                showAboutTab();
            });

            async function loadSystemInfo() {
                try {
                    const response = await fetch('/api/system/info');
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    const data = await response.json();
                    
                    // Update version in multiple places
                    document.getElementById('system-version').textContent = data.version;
                    
                    // Update LLM info
                    document.getElementById('llm-endpoint').textContent = data.llm_endpoint;
                    document.getElementById('llm-model').textContent = data.llm_model;
                    
                    // Update Whisper/ASR info
                    document.getElementById('whisper-endpoint').textContent = data.whisper_endpoint;
                    document.getElementById('asr-status').textContent = data.asr_enabled ? 'Yes' : 'No';
                    
                    if (data.asr_enabled && data.asr_endpoint) {
                        document.getElementById('asr-endpoint').textContent = data.asr_endpoint;
                        document.getElementById('asr-endpoint-row').style.display = 'block';
                    }
                } catch (error) {
                    document.getElementById('system-version').textContent = 'Failed to load';
                    document.getElementById('llm-endpoint').textContent = 'Failed to load';
                    document.getElementById('llm-model').textContent = 'Failed to load';
                    document.getElementById('whisper-endpoint').textContent = 'Failed to load';
                    document.getElementById('asr-status').textContent = 'Failed to load';
                }
            }

            async function loadShares() {
                sharesContainer.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin text-2xl"></i></div>';
                try {
                    const response = await fetch('/api/shares');
                    const shares = await response.json();
                    if (!response.ok) throw new Error(shares.error || 'Failed to load');
                    
                    if (shares.length === 0) {
                        sharesContainer.innerHTML = '<p class="text-center text-[var(--text-muted)]">You have not shared any transcripts yet.</p>';
                        return;
                    }

                    sharesContainer.innerHTML = '';
                    shares.forEach(share => {
                        const shareEl = document.createElement('div');
                        shareEl.className = 'bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]';
                        shareEl.innerHTML = `
                            <div class="flex justify-between items-start">
                                <div>
                                    <p class="font-semibold">${escapeHtml(share.recording_title)}</p>
                                    <p class="text-sm text-[var(--text-muted)]">Shared on: ${share.created_at}</p>
                                </div>
                                <button data-share-id="${share.id}" class="delete-share-btn text-red-500 hover:text-red-700 p-1"><i class="fas fa-trash"></i></button>
                            </div>
                            <div class="mt-4 flex items-center gap-4">
                                <label class="flex items-center text-sm">
                                    <input type="checkbox" data-share-id="${share.id}" data-share-prop="share_summary" class="share-checkbox h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" ${share.share_summary ? 'checked' : ''}>
                                    <span class="ml-2">Share Summary</span>
                                </label>
                                <label class="flex items-center text-sm">
                                    <input type="checkbox" data-share-id="${share.id}" data-share-prop="share_notes" class="share-checkbox h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" ${share.share_notes ? 'checked' : ''}>
                                    <span class="ml-2">Share Notes</span>
                                </label>
                            </div>
                            <div class="mt-4">
                                <input value="{{ request.url_root }}share/${share.public_id}" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm">
                            </div>
                        `;
                        sharesContainer.appendChild(shareEl);
                    });

                    document.querySelectorAll('.delete-share-btn').forEach(btn => {
                        btn.addEventListener('click', handleDeleteShare);
                    });
                    document.querySelectorAll('.share-checkbox').forEach(box => {
                        box.addEventListener('change', handleUpdateShare);
                    });

                } catch (error) {
                    sharesContainer.innerHTML = `<p class="text-center text-red-500">Error loading shares: ${error.message}</p>`;
                }
            }

            async function handleDeleteShare(event) {
                const shareId = event.currentTarget.dataset.shareId;
                if (!confirm('Are you sure you want to delete this share? This will revoke access to the public link.')) return;
                
                try {
                    // Get CSRF token
                    const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                    
                    const headers = {};
                    if (csrfToken) {
                        headers['X-CSRFToken'] = csrfToken;
                    }
                    
                    const response = await fetch(`/api/share/${shareId}`, { 
                        method: 'DELETE',
                        headers: headers
                    });
                    if (!response.ok) throw new Error('Failed to delete');
                    loadShares();
                } catch (error) {
                    alert('Error deleting share.');
                }
            }

            async function handleUpdateShare(event) {
                const shareId = event.currentTarget.dataset.shareId;
                const prop = event.currentTarget.dataset.shareProp;
                const value = event.currentTarget.checked;

                try {
                    // Get CSRF token
                    const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                    
                    const headers = { 'Content-Type': 'application/json' };
                    if (csrfToken) {
                        headers['X-CSRFToken'] = csrfToken;
                    }
                    
                    const response = await fetch(`/api/share/${shareId}`, {
                        method: 'PUT',
                        headers: headers,
                        body: JSON.stringify({ [prop]: value })
                    });
                    if (!response.ok) throw new Error('Failed to update');
                } catch (error) {
                    alert('Error updating share.');
                    event.currentTarget.checked = !value; // Revert on failure
                }
            }

            function escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }
            
            // Update footer with version
            async function updateFooter() {
                try {
                    const response = await fetch('/api/system/info');
                    if (response.ok) {
                        const data = await response.json();
                        const footerText = document.getElementById('footer-text');
                        if (footerText && data.version) {
                            footerText.textContent = `Speakr ${data.version} © {{ now.year }}`;
                        }
                    }
                } catch (error) {
                    console.log('Could not fetch version for footer');
                }
            }
            
            // Update footer on page load
            updateFooter();
        
        // Dark mode toggle functionality
        const darkModeToggle = document.getElementById('darkModeToggle');
        const darkModeIcon = document.getElementById('darkModeIcon');
        
        // Initialize dark mode based on localStorage or system preference
        function initializeDarkMode() {
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            const savedMode = localStorage.getItem('darkMode');
            
            if (savedMode === 'true' || (savedMode === null && prefersDark)) {
                document.documentElement.classList.add('dark');
                darkModeIcon.classList.remove('fa-moon');
                darkModeIcon.classList.add('fa-sun');
            } else {
                document.documentElement.classList.remove('dark');
                darkModeIcon.classList.remove('fa-sun');
                darkModeIcon.classList.add('fa-moon');
            }
        }
        
        // Toggle dark mode
        darkModeToggle.addEventListener('click', () => {
            const isDarkMode = document.documentElement.classList.toggle('dark');
            localStorage.setItem('darkMode', isDarkMode);
            
            if (isDarkMode) {
                darkModeIcon.classList.remove('fa-moon');
                darkModeIcon.classList.add('fa-sun');
            } else {
                darkModeIcon.classList.remove('fa-sun');
                darkModeIcon.classList.add('fa-moon');
            }
        });
        
        // User dropdown functionality
        const userDropdownButton = document.getElementById('userDropdownButton');
        const userDropdownMenu = document.getElementById('userDropdownMenu');
        
        userDropdownButton.addEventListener('click', () => {
            userDropdownMenu.classList.toggle('hidden');
        });
        
        // Close dropdown when clicking outside
        document.addEventListener('click', (event) => {
            if (!userDropdownButton.contains(event.target) && !userDropdownMenu.contains(event.target)) {
                userDropdownMenu.classList.add('hidden');
            }
        });
        
        // Initialize dark mode on page load
        initializeDarkMode();
        
        // Change Password Modal functionality
        const changePasswordBtn = document.getElementById('changePasswordBtn');
        const changePasswordModal = document.getElementById('changePasswordModal');
        const closeModalBtn = document.getElementById('closeModalBtn');
        const cancelBtn = document.getElementById('cancelBtn');
        const changePasswordForm = document.getElementById('changePasswordForm');
        const newPasswordInput = document.getElementById('new_password');
        const confirmPasswordInput = document.getElementById('confirm_password');
        
        // Open modal
        changePasswordBtn.addEventListener('click', () => {
            changePasswordModal.classList.remove('hidden');
            // Reset form
            changePasswordForm.reset();
        });
        
        // Close modal functions
        function closeModal() {
            changePasswordModal.classList.add('hidden');
        }
        
        closeModalBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        
        // Close modal when clicking outside
        changePasswordModal.addEventListener('click', (event) => {
            if (event.target === changePasswordModal) {
                closeModal();
            }
        });
        
        // Form validation
        changePasswordForm.addEventListener('submit', (event) => {
            if (newPasswordInput.value !== confirmPasswordInput.value) {
                event.preventDefault();
                alert('New password and confirmation do not match.');
            }
        });

        // Manage Speakers Modal functionality
        const manageSpeakersBtn = document.getElementById('manageSpeakersBtn');
        const manageSpeakersModal = document.getElementById('manageSpeakersModal');
        const closeSpeakersModalBtn = document.getElementById('closeSpeakersModalBtn');
        const closeSpeakersBtn = document.getElementById('closeSpeakersBtn');
        const deleteAllSpeakersBtn = document.getElementById('deleteAllSpeakersBtn');
        const deleteAllSpeakersModal = document.getElementById('deleteAllSpeakersModal');
        const cancelDeleteAllBtn = document.getElementById('cancelDeleteAllBtn');
        const confirmDeleteAllBtn = document.getElementById('confirmDeleteAllBtn');
        
        const speakersLoading = document.getElementById('speakersLoading');
        const speakersError = document.getElementById('speakersError');
        const speakersErrorMessage = document.getElementById('speakersErrorMessage');
        const speakersEmpty = document.getElementById('speakersEmpty');
        const speakersList = document.getElementById('speakersList');
        const speakersCount = document.getElementById('speakersCount');

        let speakers = [];

        // Open speakers modal
        manageSpeakersBtn.addEventListener('click', () => {
            manageSpeakersModal.classList.remove('hidden');
            loadSpeakers();
        });

        // Close speakers modal functions
        function closeSpeakersModal() {
            manageSpeakersModal.classList.add('hidden');
        }

        closeSpeakersModalBtn.addEventListener('click', closeSpeakersModal);
        closeSpeakersBtn.addEventListener('click', closeSpeakersModal);

        // Close modal when clicking outside
        manageSpeakersModal.addEventListener('click', (event) => {
            if (event.target === manageSpeakersModal) {
                closeSpeakersModal();
            }
        });

        // Load speakers from API
        async function loadSpeakers() {
            showLoadingState();
            
            try {
                const response = await fetch('/speakers');
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                speakers = await response.json();
                displaySpeakers();
            } catch (error) {
                console.error('Error loading speakers:', error);
                showErrorState(error.message);
            }
        }

        // Show loading state
        function showLoadingState() {
            speakersLoading.classList.remove('hidden');
            speakersError.classList.add('hidden');
            speakersEmpty.classList.add('hidden');
            speakersList.classList.add('hidden');
        }

        // Show error state
        function showErrorState(message) {
            speakersLoading.classList.add('hidden');
            speakersError.classList.remove('hidden');
            speakersEmpty.classList.add('hidden');
            speakersList.classList.add('hidden');
            speakersErrorMessage.textContent = message;
            updateSpeakersCount(0);
        }

        // Display speakers
        function displaySpeakers() {
            speakersLoading.classList.add('hidden');
            speakersError.classList.add('hidden');
            
            if (speakers.length === 0) {
                speakersEmpty.classList.remove('hidden');
                speakersList.classList.add('hidden');
                deleteAllSpeakersBtn.disabled = true;
            } else {
                speakersEmpty.classList.add('hidden');
                speakersList.classList.remove('hidden');
                deleteAllSpeakersBtn.disabled = false;
                renderSpeakersList();
            }
            
            updateSpeakersCount(speakers.length);
        }

        // Render speakers list
        function renderSpeakersList() {
            speakersList.innerHTML = '';
            
            speakers.forEach(speaker => {
                const speakerItem = createSpeakerItem(speaker);
                speakersList.appendChild(speakerItem);
            });
        }

        // Create speaker item element
        function createSpeakerItem(speaker) {
            const div = document.createElement('div');
            div.className = 'flex items-center justify-between p-3 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] hover:bg-[var(--bg-accent)] transition-colors duration-200';
            
            const createdDate = new Date(speaker.created_at).toLocaleDateString();
            const lastUsedDate = new Date(speaker.last_used).toLocaleDateString();
            
            div.innerHTML = `
                <div class="flex-1">
                    <div class="flex items-center">
                        <i class="fas fa-user text-[var(--text-muted)] mr-2"></i>
                        <span class="font-medium text-[var(--text-primary)]">${escapeHtml(speaker.name)}</span>
                    </div>
                    <div class="text-xs text-[var(--text-muted)] mt-1">
                        Used ${speaker.use_count} time${speaker.use_count !== 1 ? 's' : ''} • 
                        Last used: ${lastUsedDate} • 
                        Created: ${createdDate}
                    </div>
                </div>
                <button class="delete-speaker-btn ml-3 p-2 text-[var(--text-danger)] hover:bg-[var(--bg-danger-light)] rounded-md transition-colors duration-200" 
                        data-speaker-id="${speaker.id}" 
                        title="Delete speaker">
                    <i class="fas fa-trash text-sm"></i>
                </button>
            `;
            
            // Add delete functionality
            const deleteBtn = div.querySelector('.delete-speaker-btn');
            deleteBtn.addEventListener('click', () => deleteSpeaker(speaker.id, speaker.name));
            
            return div;
        }

        // Delete individual speaker
        async function deleteSpeaker(speakerId, speakerName) {
            if (!confirm(`Are you sure you want to delete "${speakerName}"?`)) {
                return;
            }
            
            try {
                // Get CSRF token
                const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                
                const headers = {};
                if (csrfToken) {
                    headers['X-CSRFToken'] = csrfToken;
                }
                
                const response = await fetch(`/speakers/${speakerId}`, {
                    method: 'DELETE',
                    headers: headers
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
                }
                
                // Remove from local array
                speakers = speakers.filter(s => s.id !== speakerId);
                displaySpeakers();
                showToast(`Speaker "${speakerName}" deleted successfully`);
            } catch (error) {
                console.error('Error deleting speaker:', error);
                showToast(`Failed to delete speaker: ${error.message}`, 'error');
            }
        }

        // Delete all speakers
        deleteAllSpeakersBtn.addEventListener('click', () => {
            deleteAllSpeakersModal.classList.remove('hidden');
        });

        // Cancel delete all
        cancelDeleteAllBtn.addEventListener('click', () => {
            deleteAllSpeakersModal.classList.add('hidden');
        });

        // Close delete all modal when clicking outside
        deleteAllSpeakersModal.addEventListener('click', (event) => {
            if (event.target === deleteAllSpeakersModal) {
                deleteAllSpeakersModal.classList.add('hidden');
            }
        });

        // Confirm delete all speakers
        confirmDeleteAllBtn.addEventListener('click', async () => {
            deleteAllSpeakersModal.classList.add('hidden');
            
            try {
                // Get CSRF token
                const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                
                const headers = {};
                if (csrfToken) {
                    headers['X-CSRFToken'] = csrfToken;
                }
                
                // Delete all speakers one by one
                const deletePromises = speakers.map(speaker => 
                    fetch(`/speakers/${speaker.id}`, { 
                        method: 'DELETE',
                        headers: headers
                    })
                );
                
                const results = await Promise.allSettled(deletePromises);
                
                // Check for any failures
                const failures = results.filter(result => result.status === 'rejected');
                if (failures.length > 0) {
                    console.error('Some speakers failed to delete:', failures);
                    showToast(`${failures.length} speaker(s) failed to delete`, 'error');
                }
                
                // Reload speakers list
                await loadSpeakers();
                showToast(`${speakers.length === 0 ? 'All speakers' : (results.length - failures.length) + ' speakers'} deleted successfully`);
            } catch (error) {
                console.error('Error deleting all speakers:', error);
                showToast(`Failed to delete speakers: ${error.message}`, 'error');
            }
        });

        // Update speakers count
        function updateSpeakersCount(count) {
            speakersCount.textContent = count;
        }

        // Utility function to escape HTML
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Toast notification function
        function showToast(message, type = 'success') {
            // Create toast element
            const toast = document.createElement('div');
            toast.className = `fixed top-4 right-4 z-50 px-4 py-2 rounded-lg shadow-lg transition-all duration-300 transform translate-x-full ${
                type === 'error' 
                    ? 'bg-[var(--bg-danger)] text-[var(--text-button)]' 
                    : 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'
            }`;
            toast.innerHTML = `
                <div class="flex items-center">
                    <i class="fas ${type === 'error' ? 'fa-exclamation-circle' : 'fa-check-circle'} mr-2"></i>
                    <span>${escapeHtml(message)}</span>
                </div>
            `;
            
            document.body.appendChild(toast);
            
            // Animate in
            setTimeout(() => {
                toast.classList.remove('translate-x-full');
            }, 10);
            
            // Animate out and remove
            setTimeout(() => {
                toast.classList.add('translate-x-full');
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            }, 3000);
        }

        // ===== TAG MANAGEMENT FUNCTIONALITY =====
        
        // Tag management elements
        const createTagBtn = document.getElementById('createTagBtn');
        const tagModal = document.getElementById('tagModal');
        const closeTagModalBtn = document.getElementById('closeTagModalBtn');
        const cancelTagBtn = document.getElementById('cancelTagBtn');
        const tagForm = document.getElementById('tagForm');
        const tagModalTitle = document.getElementById('tagModalTitle');
        const saveTagBtn = document.getElementById('saveTagBtn');
        
        const tagsLoading = document.getElementById('tagsLoading');
        const tagsError = document.getElementById('tagsError');
        const tagsErrorMessage = document.getElementById('tagsErrorMessage');
        const tagsEmpty = document.getElementById('tagsEmpty');
        const tagsGrid = document.getElementById('tagsGrid');

        let tags = [];
        let isEditingTag = false;

        // Load tags from API
        async function loadTags() {
            showTagsLoadingState();
            
            try {
                const response = await fetch('/api/tags');
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                tags = await response.json();
                displayTags();
            } catch (error) {
                console.error('Error loading tags:', error);
                showTagsErrorState(error.message);
            }
        }

        // Show loading state
        function showTagsLoadingState() {
            tagsLoading.classList.remove('hidden');
            tagsError.classList.add('hidden');
            tagsEmpty.classList.add('hidden');
            tagsGrid.classList.add('hidden');
        }

        // Show error state
        function showTagsErrorState(message) {
            tagsLoading.classList.add('hidden');
            tagsError.classList.remove('hidden');
            tagsEmpty.classList.add('hidden');
            tagsGrid.classList.add('hidden');
            tagsErrorMessage.textContent = message;
        }

        // Display tags
        function displayTags() {
            tagsLoading.classList.add('hidden');
            tagsError.classList.add('hidden');
            
            if (tags.length === 0) {
                tagsEmpty.classList.remove('hidden');
                tagsGrid.classList.add('hidden');
            } else {
                tagsEmpty.classList.add('hidden');
                tagsGrid.classList.remove('hidden');
                renderTagsGrid();
            }
        }

        // Render tags grid
        function renderTagsGrid() {
            tagsGrid.innerHTML = '';
            
            tags.forEach(tag => {
                const tagCard = createTagCard(tag);
                tagsGrid.appendChild(tagCard);
            });
        }

        // Create tag card element
        function createTagCard(tag) {
            const div = document.createElement('div');
            div.className = 'bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] hover:shadow-md transition-shadow duration-200';
            
            div.innerHTML = `
                <div class="flex items-start justify-between mb-3">
                    <div class="flex items-center">
                        <div class="w-4 h-4 rounded-full mr-3" style="background-color: ${escapeHtml(tag.color)}"></div>
                        <h3 class="font-semibold text-[var(--text-primary)]">${escapeHtml(tag.name)}</h3>
                    </div>
                    <div class="flex space-x-1">
                        <button class="edit-tag-btn p-1 text-[var(--text-muted)] hover:text-[var(--text-accent)] rounded" 
                                data-tag-id="${tag.id}" title="Edit tag">
                            <i class="fas fa-edit text-sm"></i>
                        </button>
                        <button class="delete-tag-btn p-1 text-[var(--text-muted)] hover:text-[var(--text-danger)] rounded" 
                                data-tag-id="${tag.id}" title="Delete tag">
                            <i class="fas fa-trash text-sm"></i>
                        </button>
                    </div>
                </div>
                
                <div class="space-y-2 text-sm text-[var(--text-muted)]">
                    ${tag.custom_prompt ? `
                        <div>
                            <span class="font-medium">Custom Prompt:</span>
                            <span class="text-xs">${escapeHtml(tag.custom_prompt.substring(0, 60))}${tag.custom_prompt.length > 60 ? '...' : ''}</span>
                        </div>
                    ` : ''}
                    
                    ${tag.default_language || tag.default_min_speakers || tag.default_max_speakers ? `
                        <div class="pt-2 border-t border-[var(--border-secondary)]">
                            <span class="font-medium text-xs">ASR Defaults:</span>
                            <div class="flex flex-wrap gap-2 mt-1">
                                ${tag.default_language ? `<span class="inline-flex items-center px-2 py-1 rounded-full text-xs bg-[var(--bg-accent)] text-[var(--text-accent)]">Lang: ${escapeHtml(tag.default_language)}</span>` : ''}
                                ${tag.default_min_speakers ? `<span class="inline-flex items-center px-2 py-1 rounded-full text-xs bg-[var(--bg-accent)] text-[var(--text-accent)]">Min: ${tag.default_min_speakers}</span>` : ''}
                                ${tag.default_max_speakers ? `<span class="inline-flex items-center px-2 py-1 rounded-full text-xs bg-[var(--bg-accent)] text-[var(--text-accent)]">Max: ${tag.default_max_speakers}</span>` : ''}
                            </div>
                        </div>
                    ` : ''}
                </div>
            `;
            
            // Add event listeners
            const editBtn = div.querySelector('.edit-tag-btn');
            const deleteBtn = div.querySelector('.delete-tag-btn');
            
            editBtn.addEventListener('click', () => editTag(tag));
            deleteBtn.addEventListener('click', () => deleteTag(tag.id, tag.name));
            
            return div;
        }

        // Create tag modal functionality
        createTagBtn.addEventListener('click', () => {
            openTagModal();
        });

        // Close tag modal functions
        function closeTagModal() {
            tagModal.classList.add('hidden');
            tagForm.reset();
            isEditingTag = false;
            document.getElementById('tagId').value = '';
        }

        closeTagModalBtn.addEventListener('click', closeTagModal);
        cancelTagBtn.addEventListener('click', closeTagModal);

        // Close modal when clicking outside
        tagModal.addEventListener('click', (event) => {
            if (event.target === tagModal) {
                closeTagModal();
            }
        });

        // Open tag modal for create
        function openTagModal(tag = null) {
            if (tag) {
                // Edit mode
                isEditingTag = true;
                tagModalTitle.textContent = 'Edit Tag';
                saveTagBtn.innerHTML = '<i class="fas fa-save mr-2"></i> Update Tag';
                
                // Populate form
                document.getElementById('tagId').value = tag.id;
                document.getElementById('tagName').value = tag.name;
                document.getElementById('tagColor').value = tag.color;
                document.getElementById('tagCustomPrompt').value = tag.custom_prompt || '';
                
                if (document.getElementById('tagLanguage')) {
                    document.getElementById('tagLanguage').value = tag.default_language || '';
                }
                if (document.getElementById('tagMinSpeakers')) {
                    document.getElementById('tagMinSpeakers').value = tag.default_min_speakers || '';
                }
                if (document.getElementById('tagMaxSpeakers')) {
                    document.getElementById('tagMaxSpeakers').value = tag.default_max_speakers || '';
                }
            } else {
                // Create mode
                isEditingTag = false;
                tagModalTitle.textContent = 'Create Tag';
                saveTagBtn.innerHTML = '<i class="fas fa-save mr-2"></i> Save Tag';
                tagForm.reset();
                document.getElementById('tagColor').value = '#3B82F6';
            }
            
            tagModal.classList.remove('hidden');
        }

        // Edit tag
        function editTag(tag) {
            openTagModal(tag);
        }

        // Delete tag
        async function deleteTag(tagId, tagName) {
            if (!confirm(`Are you sure you want to delete "${tagName}"?`)) {
                return;
            }
            
            try {
                const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                
                const headers = {};
                if (csrfToken) {
                    headers['X-CSRFToken'] = csrfToken;
                }
                
                const response = await fetch(`/api/tags/${tagId}`, {
                    method: 'DELETE',
                    headers: headers
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
                }
                
                // Remove from local array
                tags = tags.filter(t => t.id !== tagId);
                displayTags();
                showToast(`Tag "${tagName}" deleted successfully`);
            } catch (error) {
                console.error('Error deleting tag:', error);
                showToast(`Failed to delete tag: ${error.message}`, 'error');
            }
        }

        // Save tag form submission
        tagForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(tagForm);
            const tagData = {
                name: formData.get('name'),
                color: formData.get('color'),
                custom_prompt: formData.get('custom_prompt') || null,
                default_language: formData.get('default_language') || null,
                default_min_speakers: formData.get('default_min_speakers') ? parseInt(formData.get('default_min_speakers')) : null,
                default_max_speakers: formData.get('default_max_speakers') ? parseInt(formData.get('default_max_speakers')) : null
            };
            
            try {
                const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
                
                const headers = { 'Content-Type': 'application/json' };
                if (csrfToken) {
                    headers['X-CSRFToken'] = csrfToken;
                }
                
                let url = '/api/tags';
                let method = 'POST';
                
                if (isEditingTag) {
                    url += `/${formData.get('tag_id')}`;
                    method = 'PUT';
                }
                
                const response = await fetch(url, {
                    method: method,
                    headers: headers,
                    body: JSON.stringify(tagData)
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
                }
                
                const savedTag = await response.json();
                
                if (isEditingTag) {
                    // Update existing tag in local array
                    const index = tags.findIndex(t => t.id === savedTag.id);
                    if (index !== -1) {
                        tags[index] = savedTag;
                    }
                    showToast(`Tag "${savedTag.name}" updated successfully`);
                } else {
                    // Add new tag to local array
                    tags.push(savedTag);
                    showToast(`Tag "${savedTag.name}" created successfully`);
                }
                
                displayTags();
                closeTagModal();
            } catch (error) {
                console.error('Error saving tag:', error);
                showToast(`Failed to save tag: ${error.message}`, 'error');
            }
        });
        
        // Check for URL hash and show appropriate tab
        const urlHash = window.location.hash.substring(1); // Remove the '#' symbol
        if (urlHash === 'tags') {
            showTagsTab();
        } else if (urlHash === 'shares') {
            showSharesTab();
        } else if (urlHash === 'about') {
            showAboutTab();
        } else {
            // Default to account tab
            showAccountTab();
        }
    });
    </script>
</body>
</html>
